"""
服务管理服务层
"""
from models import Service, ServiceType
from extension import db
from mappers.service_mapper import ServiceMapper, ServiceTypeMapper
from .base_service import BaseService


class ServiceService(BaseService):
    """服务业务逻辑"""
    
    def __init__(self):
        super().__init__(Service)
        self.mapper = ServiceMapper()
        self.type_mapper = ServiceTypeMapper()
    
    def get_services_with_filters(self, page=1, per_page=10, name=None, type_id=None):
        """获取服务列表（支持多条件过滤）"""
        query = Service.query
        
        if name:
            query = query.filter(Service.name.like(f'%{name}%'))
        if type_id is not None:
            query = query.filter(Service.type_id == type_id)
        
        return query.paginate(page=page, per_page=per_page, error_out=False)
    
    def create_service(self, name, price, description=None, type_id=None):
        """创建服务"""
        # 验证服务类型是否存在（如果提供了type_id）
        if type_id is not None:
            if not ServiceType.query.get(type_id):
                raise ValueError(f'无效的服务类型ID: {type_id}')
        
        service = Service(
            name=name,
            price=float(price),
            description=description or '',
            type_id=type_id
        )
        db.session.add(service)
        db.session.commit()
        return service
    
    def update_service(self, service_id, **data):
        """更新服务信息"""
        service = self.get_by_id(service_id)
        if not service:
            return None
        
        # 验证服务类型是否存在（如果提供了type_id）
        if 'type_id' in data and data['type_id'] is not None:
            if not ServiceType.query.get(data['type_id']):
                raise ValueError(f'无效的服务类型ID: {data["type_id"]}')
        
        for key, value in data.items():
            if hasattr(service, key) and value is not None:
                setattr(service, key, value)
        
        db.session.commit()
        return service
    
    def delete_service(self, service_id):
        """删除服务"""
        service = self.get_by_id(service_id)
        if not service:
            return False
        
        db.session.delete(service)
        db.session.commit()
        return True
    
    def get_service_types(self):
        """获取所有服务类型"""
        return ServiceType.query.all()
    
    def create_service_type(self, name, description=None):
        """创建服务类型"""
        if ServiceType.query.filter_by(name=name).first():
            raise ValueError('服务类型名称已存在')
        
        service_type = ServiceType(
            name=name,
            description=description or ''
        )
        db.session.add(service_type)
        db.session.commit()
        return service_type
    
    def get_services_paginated_dto(self, page=1, per_page=10, name=None, type_id=None):
        """获取服务列表（返回DTO）"""
        paginated = self.get_services_with_filters(page, per_page, name, type_id)
        return {
            'list': [self.mapper.to_dict(service) for service in paginated.items],
            'total': paginated.total,
            'page': paginated.page,
            'pageSize': paginated.per_page,
            'pages': paginated.pages
        }
    
    def get_service_dto(self, service_id):
        """获取服务详情（返回DTO）"""
        service = self.get_by_id(service_id)
        return self.mapper.to_dict(service) if service else None
    
    def create_service_dto(self, name, price, description=None, type_id=None):
        """创建服务（返回DTO）"""
        service = self.create_service(name, price, description, type_id)
        return self.mapper.to_dict(service)
    
    def update_service_dto(self, service_id, **data):
        """更新服务（返回DTO）"""
        service = self.update_service(service_id, **data)
        return self.mapper.to_dict(service) if service else None
    
    def get_service_types_dto(self):
        """获取服务类型（返回DTO）"""
        service_types = self.get_service_types()
        return self.type_mapper.to_list(service_types)
